
const { config, colorOption } = getApp().globalData;

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 图片列表
    fileList: {
      type: Object,
      value: [],
    },
    // 图片上传数量
    maxNumber: {
      type: Number,
      value: 1,
    },
    // 展示类型
    type: {
      type: String,
      value: "avatar", // avatar(头像) || list(图片列表) || idCard(身份证)
    },
    disabled:{
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    config,
    localImgSrc:config.localImgSrc,
    colorOption,
    idcardType: 0, // 身份证正反面 0 正面 1 反面
  },

  // 组件生命周期函数
  lifetimes: {
    created() {},
    attached() {
      // 身份证
      if (this.properties.type === "idCard") {
        let { fileList } = this.properties;
        fileList = [fileList[0] || "", fileList[1] || ""];
        this.setData({
          fileList,
        });
        // console.log(this.properties.fileList);
      }
    },
    ready() {},
    moved() {},
    detached() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 选择图片上传方式
    chooseUploadMethod: function (e) {
      const that = this;
      // 身份证标明 正反面
      if (that.properties.type === "idCard") {
        const { index: idcardType } = e.currentTarget.dataset;
        that.setData({
          idcardType,
        });
      }
      wx.showActionSheet({
        itemList: ["从相册中选择", "拍照"],
        success: function (res) {
          if (res.tapIndex === 0) {
            that.chooseUploadImage("album"); // 相册
          } else if (res.tapIndex === 1) {
            that.chooseUploadImage("camera"); // 相机
          }
        },
      });
    },

    // 选择相册图片或拍照
    chooseUploadImage(sourceType) {
      const that = this;
      let count = that.properties.maxNumber - that.properties.fileList.length;
      if (this.properties.type === "idCard") count = 1;
      wx.chooseMedia({
        count, // 图片个数
        mediaType: ["image"],
        sourceType: [sourceType],
        sizeType: ["compressed"],
        success(res) {
          that.uploadFile(res.tempFiles);
        },
      });
    },
    // 预览图片
    previewImage(e) {
      const { index: currentIndex } = e.currentTarget.dataset; // 获取当前图片索引
      const imgList = this.properties.fileList.map(s=>config.localImgSrc + s); // 图片数组

      wx.previewImage({
        current: imgList[currentIndex],
        urls: imgList,
      });
    },
    // 删除图片
    deleteImage: function (e) {
      const that = this;
      const { index } = e.currentTarget.dataset;
      let { fileList, idcardType } = that.properties;

      wx.showModal({
        title: "提示",
        content: "确定要删除此图片吗？",
        success: function (res) {
          if (res.confirm) {
            // 移除指定索引的图片
            if (that.properties.type === "idCard")
              fileList.splice(index, 1, "");
            else fileList.splice(index, 1);

            that.setData({
              fileList,
            });
            that.triggerEvent("onUploaded", fileList); // 返回图片列表数据
          }
        },
      });
    },
    // 上传图片
    uploadFile(tempFiles) {
      wx.showLoading({
        title: "上传中...",
      });
      const that = this;
      let { fileList } = that.data;
      const { basePath, uploadUrl } = that.data.config;
      const uploadPromises = tempFiles.map((file) => {
        return new Promise((resolve, reject) => {
          wx.uploadFile({
            url: basePath + uploadUrl,
            filePath: file.tempFilePath,
            name: "file",
            header: {
              "content-type": "multipart/form-data",
              Authorization: "Bearer " + (wx.getStorageSync("token") || ""),
            },
            success(res) {
              try {
                const data = JSON.parse(res.data);
                if (data.code !== 200) {
                  reject(data.msg || "上传图片失败");
                } else {
                  resolve(data.fileName);
                }
              } catch (error) {
                reject(error);
              }
            },
            fail(err) {
              reject(err);
            },
          });
        });
      });

      Promise.all(uploadPromises)
        .then((imagelist) => {
          // 头像
          if (that.properties.type === "avatar") {
            that.setData({
              fileList: [imagelist[0]],
            });
            that.triggerEvent("onUploaded", that.data.fileList); // 返回图片列表数据
            return;
          }
          // 身份证
          if (that.properties.type === "idCard") {
            that.setData({
              [`fileList[${idcardType}]`]: imagelist[0],
            });
            that.triggerEvent("onUploaded", that.data.fileList); // 返回图片列表数据
            return;
          }
          const updatedFileList = [...fileList, ...imagelist];
          that.setData({
            fileList: updatedFileList,
          });
          that.triggerEvent("onUploaded", updatedFileList); // 返回图片列表数据
        })
        .catch(() => {
          wx.showToast({
            title: "图片上传失败",
            icon: "error",
            duration: 2000,
          });
        })
        .finally(() => {
          wx.hideLoading();
        });
    },
  },
});
